package com.medata.controller;
/*
 *@ClassName: TestController
 *@Description: TODO
 *@author: zb
 *@date: 2019-03-23 8:11
 *@version: 1.0
 */

import com.medata.dataObject.Account;
import com.medata.dataObject.Databaselist;
import com.medata.dataObject.UserRole;
import com.medata.service.DatabaselistService;
import com.medata.service.GlobalsettingService;
import com.medata.service.TemplatefieldsService;
import com.medata.service.impl.AccountServiceImpl;
import com.medata.service.impl.UserRoleServiceImpl;
import com.medata.utils.MenuUtil;
import com.medata.utils.SolrUtils;
import com.medata.vo.SysMenu;
import com.medata.vo.UrlVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


@Controller
@Slf4j
@Api
public class LoginController {
    @Value("${perfix}")
    private String perfix;
    @Autowired
    private GlobalsettingService globalsettingService;
    @Autowired
    private DatabaselistService databaselistService;
    @Autowired
    private TemplatefieldsService templatefieldsService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private UserRoleServiceImpl userRoleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView login(String name, String password, HttpServletResponse response)throws IOException {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        ModelAndView mv=new ModelAndView();
        mv.addObject("username",name);
        List<UrlVo> urlList=new ArrayList<>();
        try {
            subject.login(token);
            Account account=accountService.findByUserName(name);
            UserRole userRole=userRoleService.findByRoleId(account.getRoleId());
            if (account.getStatus()==null||!account.getStatus()){
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script type='text/javascript'>alert('该账户已被停用');history.go(-1)</script>");
                writer.flush();
                writer.close();
            }
            String role=userRole.getRoleName();
            if (role.equals("编目人员")){
                List<Databaselist> all = new ArrayList<>();
                String dbids = account.getDbids();
                if (dbids!=null&&!dbids.isEmpty()){
                    String[] ids=dbids.split(",");
                    for (String i:ids){
                        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(i));
                        all.add(databaselist);
                    }
                }
                for (Databaselist databaselist:all){
                    UrlVo urlVo=new UrlVo();
                    urlVo.setUrl("editor/zlpost/"+databaselist.getDbid());
                    urlVo.setDesc(databaselist.getDbtitle());
                    urlList.add(urlVo);
                }
                mv.addObject("UrlList",urlList);
                mv.setViewName("index");
            }if (role.equals("管理员")){
                mv.setViewName("index");
            }if ((role.equals("审核人员"))){
                mv.setViewName("index");
            }
        }catch (AuthenticationException ae){
            log.info("用户名or密码错误or错误次数过多");
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String s = ops.get(name);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            if (s!=null){
                if (Integer.valueOf(s)>5){
                    writer.print("<script type='text/javascript'>alert('密码错误次数太多,请稍后登入');history.go(-1)</script>");
                    writer.flush();
                    writer.close();
                    return null;
                }
            }
            writer.print("<script type='text/javascript'>alert('账号or密码错误:错误5次以上将锁定账户');history.go(-1)</script>");
            writer.flush();
            writer.close();
            return null;
        }
        return mv;
    }
    @RequestMapping(value = "/notLogin", method = RequestMethod.GET)
    public String notLogin() {
        return "notlogin";
    }

    @RequestMapping(value = "/notRole", method = RequestMethod.GET)
    public String notRole() {
        return "error/403";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        ModelAndView mv=new ModelAndView();
        mv.setViewName("notlogin");
        return mv;
    }

    @RequestMapping(value = "/menuList",method = RequestMethod.GET)
    @ResponseBody
    public List<SysMenu> get(){
        Object username = SecurityUtils.getSubject().getPrincipal();
        String name = ObjectUtils.nullSafeToString(username);
        Account account = accountService.findByUserName(name);
        List<SysMenu> sLists=new ArrayList<>();
        if (account.getRoleId()==2){
            List<Databaselist> all = new ArrayList<>();
            String dbids = account.getDbids();
            if (dbids!=null&&!dbids.isEmpty()){
                String[] ids=dbids.split(",");
                for (String i:ids){
                    Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(i));
                    all.add(databaselist);
                }
            }
            sLists = MenuUtil.getEditorMenu(perfix,all);
        }else if (account.getRoleId()==1){
            sLists=MenuUtil.getAdminMenu(perfix);
        }else if (account.getRoleId()==4){
            List<Databaselist> all = databaselistService.findAll();
            sLists=MenuUtil.getAuditorMenu(perfix,all);
        }
        return sLists;
    }

    //    @RequestMapping("/{index}")
//    public String index(@PathVariable String index){
//        return index;
//    }
    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public String welcome(){
        return "welcome";
    }

    @RequestMapping(value = "/start",method = RequestMethod.GET)
    @ResponseBody
    public String start(){
        List<Databaselist> databaselists = databaselistService.findAll();
        for (Databaselist database:databaselists){
            SolrUtils.insertCore(globalsettingService,database.getDbname());
        }
        return "初始化完毕";
    }

    @RequestMapping("/")
    public String index(){
        return "notlogin";
    }

    @RequestMapping(value = "/restartSession",method = RequestMethod.GET)
    @ResponseBody
    public String restartSession(){
        return null;
    }


}
